const Subscription = require('egg').Subscription;
const CONFIG = require('../../config/cms.config')

// 微信 access_token 获取
class UpdateAccessToken extends Subscription {
    // 通过 schedule 属性来设置定时任务的执行间隔等配置
    static get schedule() {
        return {
            interval: '110m',
            type: 'all',
            immediate: true
        };
    }

    // subscribe 是真正定时任务执行时被运行的函数
    async subscribe() {
        const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${CONFIG.wx.APPID}&secret=${CONFIG.wx.APPSECRET}`;
        try {
            const res = await this.ctx.curl(url, {
                dataType: 'json',
            });
            console.log('获取accessToken', res.data);
            this.ctx.app.cache.wx.accessToken = res.data.access_token;
            this.ctx.app.cache.wx.tokenCreateTime = Date.now();
            this.ctx.app.cache.wx.expiresIin = res.data.expires_in;
        } catch (e) {
            console.log('获取失败', e)
        }
    }
}

module.exports = UpdateAccessToken;